// 类 + 类方法的形式
const { exec } = require('../db/index')
const jwt = require('jsonwebtoken')
const { secretKey } = require('../config/index')

class HomeService {
  async login(ctx) {
    const { username, password } = ctx.request.body;
    const data = await exec(`select * from users where username=? and password=?`,
      [username, password]
    )
    const token = jwt.sign({ ...data[0] }, secretKey, {
      expiresIn: '24h'
    })
    if (data.length) {
      return {
        code: 0,
        msg: '登陆成功',
        token
      }
    } else {
      return {
        code: -1,
        msg: '登陆失败',
      }
    }
  }

  async register(ctx) {
    // 参数  判断有没有
    const { username, password, nickname } = ctx.request.body;
    const data = await exec(`select * from users where username=? and password=?`,
      [username, password]
    )
    if (data.length) {
      return {
        code: -1,
        msg: '账号已经存在'
      }
    } else {
      const data = await exec(`insert into users (username, password,nickname) values (?,?,?)`, [username, password, nickname]);
      if (data.affectedRows) {
        return {
          code: 0,
          msg: '注册成功',
          id: data.insertId
        }
      } else {
        return {
          code: -1,
          msg: '注册失败'
        }
      }
    }
  }
  // 
}

module.exports = new HomeService